import {
  BaseRepository,
  indexBuilder,
  paginateBuilder,
  showBuilder,
} from '@libs/common/repository';
import { Inject, Injectable } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { EntityManager, Repository } from 'typeorm';

import { ProviderKey } from './device-road.providers';
import {
  FindDeviceRoadDto,
  IndexDeviceRoadDto,
  ShowDeviceRoadDto,
} from './dto/device-road.dto';
import { DeviceRoad } from './entities/device-road.entity';
import { generateDeviceRoads } from './utils';

@Injectable()
export class DeviceRoadService extends BaseRepository {
  @Inject(ProviderKey)
  private repository: Repository<DeviceRoad>;

  private readonly entityManager: EntityManager;

  async index(dto: IndexDeviceRoadDto, mcuid: string) {
    const raw = indexBuilder({
      dto,
      repository: this.repository,
    });

    raw.andWhere('mcuid = :mcuid', { mcuid });

    const res = await paginateBuilder(raw, dto);

    return res;
  }

  async show<D extends ShowDeviceRoadDto = ShowDeviceRoadDto>(
    dto: D,
    mcuid: string,
  ) {
    const builder = showBuilder(this.repository, dto)?.andWhere(
      'deviceRoad.mcuid = :mcuid',
      { mcuid },
    );

    if (dto.id) {
      return builder?.getOne();
    } else if (dto.ids) {
      return builder?.getMany() || [];
    }
  }

  find(dto: FindDeviceRoadDto) {
    return this.repository.find({ where: dto });
  }

  async initializeData(mcuid: string) {
    console.log('初始化数据');
    const name = '零食兑换机';
    const descri = '公司设备';
    const roads = generateDeviceRoads(mcuid);

    const axis: DeviceRoad[] = plainToInstance(
      DeviceRoad,
      roads.map((road) => ({ ...road, name, descri })),
    );

    return this.repository.save(axis);
  }
}
